package cc.rengu.igas.channel.alipay.core.service.trans;

import cc.rengu.igas.channel.alipay.common.constant.AlipayConfigConstant;
import cc.rengu.igas.channel.alipay.common.constant.AlipayTreeNodeConstant;
import cc.rengu.igas.channel.alipay.common.enums.RespCodeEnum;
import cc.rengu.igas.channel.alipay.core.model.ChnlBizResponse;
import cc.rengu.igas.channel.alipay.core.service.base.AppAuthService;
import cc.rengu.igas.channel.alipay.core.service.base.UserService;
import cc.rengu.igas.channel.alipay.facade.request.AliGetAppAuthCodeRequest;
import cc.rengu.igas.channel.alipay.facade.request.AliGetAuthCodeRequest;
import cc.rengu.igas.channel.alipay.facade.response.AliGetAppAuthCodeResponse;
import cc.rengu.igas.channel.alipay.facade.response.AliGetAuthCodeResponse;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.DstChannelCfg;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 获取商户应用授权URL
 */
public class AliGetAppAuthCodeService extends AppAuthService {
    @Override
    protected Object beforeBizProcess() throws Exception {
        AliGetAppAuthCodeRequest aliGetAppAuthCodeRequest = new AliGetAppAuthCodeRequest();
        ConvertUtil.convertOutput(aliGetAppAuthCodeRequest);
        return aliGetAppAuthCodeRequest;
    }

    @Override
    protected ChnlBizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        AliGetAppAuthCodeRequest aliGetAppAuthCodeRequest = (AliGetAppAuthCodeRequest) request;
        AliGetAppAuthCodeResponse aliGetAppAuthCodeResponse = new AliGetAppAuthCodeResponse();
        aliGetAppAuthCodeResponse.setHeader(aliGetAppAuthCodeRequest.getHeader());

        DstChannelCfg dstChannelCfg = (DstChannelCfg) xmlTreeUtil.getXmlTreeObjectValue(AlipayTreeNodeConstant.DST_CHANNEL_CFG, DstChannelCfg.class);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.TXN_NUM, aliGetAppAuthCodeRequest.getHeader().getTxnNum());
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("app_id", dstChannelCfg.getAppId());
        if (StringUtil.isEmptyOrNull(aliGetAppAuthCodeRequest.getAppType())) {
            paramMap.put("application_type", "WEBAPP");
        } else {
            paramMap.put("application_type", aliGetAppAuthCodeRequest.getAppType());
        }
        paramMap.put("redirect_uri", URLEncoder.encode(aliGetAppAuthCodeRequest.getRedirectUrl(), "UTF-8"));
        paramMap.put("state", aliGetAppAuthCodeRequest.getState());
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam sysParam = sysParamService.getSysParamInfo(aliGetAppAuthCodeRequest.getHeader().getInstId(),
                AlipayConfigConstant.ALIPAY_CONF_NODE, AlipayConfigConstant.MCHNT_APP_AUTH_CODE_URL);
        if (sysParam == null) {
            throw new BizException(RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespCode(), RespCodeEnum.CONFIG_PARAM_NOT_EXIST.getRespDesc());
        }
        String requestUrl = generateHttpUrl(sysParam.getParamValue(), paramMap);
        aliGetAppAuthCodeResponse.setAppAuthUrl(requestUrl);
        aliGetAppAuthCodeResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        aliGetAppAuthCodeResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        ChnlBizResponse chnlBizResponse = new ChnlBizResponse();
        chnlBizResponse.setResult(aliGetAppAuthCodeResponse);
        return chnlBizResponse;
    }

    @Override
    protected void afterBizProcess(ChnlBizResponse response) throws Exception {
        AliGetAppAuthCodeResponse aliGetAppAuthCodeResponse = (AliGetAppAuthCodeResponse) response.getResult();
        ConvertUtil.convertInput(aliGetAppAuthCodeResponse);
    }

    /**
     * 根据配置拼装URL地址
     *
     * @param transUrl    URL地址
     * @param urlParamMap URL参数集合
     * @return URL地址
     */
    private String generateHttpUrl(String transUrl, Map<String, String> urlParamMap) {
        StringBuilder requestUrlParam = new StringBuilder();
        for (String key : urlParamMap.keySet()) {
            requestUrlParam.append(key).append("=").append(urlParamMap.get(key)).append("&");
        }
        return transUrl + requestUrlParam.substring(0, requestUrlParam.length() - 1);
    }
}
